package com.ycfmedical.bed.model;

import static com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil.StrC16T10;
import static java.lang.Thread.MIN_PRIORITY;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import com.ycfmedical.bed.bean.BodySignParameterInfo;
import com.ycfmedical.bed.listener.IreceiveData;
import com.ycfmedical.bed.listener.IvsModel;
import com.ycfmedical.bed.local.DataManager;
import com.ycfmedical.bed.serverdata.DBUtil;

import android.os.StrictMode;

import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.log.XLog;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 生命体征界面Model Created by Administrator on 2017/3/22.
 */

public class VsModel implements IvsModel
{
    private static VsModel vsModel = new VsModel();

    private IreceiveData ireceiveData; // 传数据到生命体征接口

    private boolean flag = true;

    DBUtil dbUtil = DBUtil.getInstance();

    // 当前生命体征数据

    String LocalheartRate = "60";

    String LocalBreathe = "20";

    String LocalBodyState = "2C";

    public static IvsModel getVsModel()
    {

        return vsModel;
    }

    private VsModel()
    {

    }

    private class UpBodySigndata extends Thread
    {
        @Override
        public void run()
        {
            if (android.os.Build.VERSION.SDK_INT > 9)
            {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
            // 获取当前时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); // 设置时间格式
            Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
            String currentTimes = formatter.format(curDate);
            // 存储生命体征数据
            dbUtil.save_tizheng(currentTimes,
                    DataManager.getInstance().getUser().getId() + "",
                    LocalheartRate + "",
                    LocalBreathe + "",
                    LocalBodyState + "",
                    "0000");
        }
    }

    @Override
    public void setReceiveService(IreceiveData ireceiveData)
    {
        this.ireceiveData = ireceiveData;
    }

    @Override
    public boolean receiveData(String data)
    {
        BusProvider.getBus()
            .toObservableSticky(BodySignParameterInfo.class)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
                .sample(1000, TimeUnit.MILLISECONDS)
            .onBackpressureDrop()
            .subscribe(new Subscriber<BodySignParameterInfo>()
            {
                @Override
                public void onStart() {
                    super.onStart();
                    request(1);
                }

                @Override
                public void onCompleted()
                {
                    if (!isUnsubscribed()) {
                        this.unsubscribe();
                    }
                }
                
                @Override
                public void onError(Throwable e)
                {
                    XLog.e("VsModel","" + e);
                }
                
                @Override
                public void onNext(BodySignParameterInfo BodySignParameterInfo)
                {
                    String HeartRate = BodySignParameterInfo.getHeartRate();
                    LocalheartRate = HeartRate;
                    String breathe = BodySignParameterInfo.getBreathe();
                    LocalBreathe = breathe;
                    String bodyState = BodySignParameterInfo.getBodyState();
                    LocalBodyState = bodyState;
                    setData(HeartRate + breathe);
                    UpBodySigndata upBodySigndata = new UpBodySigndata();
                    upBodySigndata.setPriority(MIN_PRIORITY);
                    upBodySigndata.start();
                    request(1);
                }
            });

        return flag;
    }

    /**
     * 使用服务保存数据的传数据方法
     */
    public void setData(String data)
    {
        XLog.e("SJH","有新数据来");
        rx.Observable.create(new rx.Observable.OnSubscribe<String>()
        {
            @Override
            public void call(Subscriber<? super String> subscriber)
            {
                subscriber.onNext(data);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.immediate()).subscribe(
                new Subscriber<String>()
                {
                    @Override
                    public void onCompleted()
                    {
                        // 先判断再解除绑定
                        if (!isUnsubscribed())
                        {
                            unsubscribe();
                        }
                    }

                    @Override
                    public void onError(Throwable e)
                    {

                    }

                    @Override
                    public void onNext(String data)
                    {
                        ArrayList<Float> fdata = new ArrayList<Float>();
                        fdata.add((float)StrC16T10(data.substring(0, 2)));
                        fdata.add((float)StrC16T10(data.substring(2, 4)));
                        ireceiveData.receiveData(fdata);
                    }
                });
    }

}
